package com.virgo.demo.market.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.virgo.common.entity.ListDataVo;
import com.virgo.common.utils.ICommonUtils;
import com.virgo.demo.market.converter.FriendLinkConverter;
import com.virgo.demo.market.domain.FriendLinkDo;
import com.virgo.demo.market.domain.bo.FriendLinkBo;
import com.virgo.demo.market.domain.vo.FriendLinkVo;
import com.virgo.demo.market.mapper.FriendLinkMapper;
import com.virgo.demo.market.service.FriendLinkService;
import com.virgo.web.utils.IRequestUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
@RequiredArgsConstructor
public class FriendLinkServiceImpl extends ServiceImpl<FriendLinkMapper, FriendLinkDo> implements FriendLinkService {

	private final FriendLinkMapper friendLinkMapper;

	private final FriendLinkConverter friendLinkConverter;

	/**
	 * 编辑友情链接
	 * @param friendLinkBo FriendLinkBo
	 */
	@Override
	public void saveFriendLink(FriendLinkBo friendLinkBo) {
		FriendLinkDo friendLinkDo = new FriendLinkDo();
		BeanUtils.copyProperties(friendLinkBo,friendLinkDo);
		if (ObjectUtils.isEmpty(friendLinkDo.getId()) || friendLinkDo.getId().compareTo(0L) < 1) {
			save(friendLinkDo);
			return;
		}
		updateById(friendLinkDo);
	}

	/**
	 * 删除友情链接
	 * @param ids String
	 */
	@Override
	public void deleteFriendLink(String ids) {
		List<Long> idList = Arrays.asList(ICommonUtils.stringToArray(ids, ","));
		removeByIds(idList);
	}

	/**
	 * 友情链接列表
	 * @param request HttpServletRequest
	 * @return ListDataVo<FriendLinkVo>
	 */
	@Override
	public ListDataVo<FriendLinkVo> findList(HttpServletRequest request) {
		long currentPage = IRequestUtils.getLong(request,"page");
		long pageSize = IRequestUtils.getLong(request,"pageSize");
		currentPage = Math.max(currentPage,1);
		pageSize = Math.max(pageSize,10);

		LambdaQueryWrapper<FriendLinkDo> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.orderByDesc(FriendLinkDo::getId);

		String name = IRequestUtils.getString(request,"name","");
		if (!ObjectUtils.isEmpty(name)) {
			queryWrapper.like(FriendLinkDo::getName,name);
		}

		Page<FriendLinkDo> page = new Page<>(currentPage, pageSize);
		IPage<FriendLinkDo> iPage = friendLinkMapper.selectPage(page, queryWrapper);
		return new ListDataVo<>(iPage.getTotal(),iPage.getPages(),friendLinkConverter.convert(iPage.getRecords(), FriendLinkVo.class));
	}
}